package com.lottery.module.dao;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;

import com.google.common.collect.Lists;
import com.lottery.entity.LotteryInfo;

@Repository
public class LotteryInfoDao {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  public LotteryInfo findNotEndInfo() {
    StringBuffer sb = new StringBuffer();
    sb.append("select * from lottery_info where has_end = 0");
    List<LotteryInfo> infos = this.jdbcTemplate.query(sb.toString(), new BeanPropertyRowMapper<LotteryInfo>(LotteryInfo.class));
    if (CollectionUtils.isEmpty(infos)) {
      return null;
    }
    Assert.isTrue(infos.size() == 1, "lottery not end size large 1");
    return (LotteryInfo) infos.get(0);
  }

  public void insert(LotteryInfo info) {
    StringBuffer sb = new StringBuffer();
    sb.append("insert into lottery_info (periods,sale_total_money,sale_total_count,");
    sb.append(" has_end,lottery_time,lottery_result,create_time,update_time,version)");
    sb.append("values (?,?,?,?,?,?,?,?,?)");

    List<Object> params = Lists.newArrayList();
    params.add(info.getPeriods());
    params.add(info.getSaleTotalMoney());
    params.add(Integer.valueOf(info.getSaleTotalCount()));
    params.add(Boolean.valueOf(info.isHasEnd()));
    params.add(info.getLotteryTime());
    params.add(info.getLotteryResult());
    params.add(info.getCreateTime());
    params.add(info.getUpdateTime());
    params.add(Integer.valueOf(info.getVersion()));
    this.jdbcTemplate.update(sb.toString(), params.toArray());
  }
}